import request from './request'

const amisRequest = async ({ url, method = 'get', data, responseType, config = {}, headers }) => {
  config = {
    ...config,
    headers,
    responseType
  }

  try {
    let response;
    switch (method) {
      case 'get':
        response = await request.get(url, data, config);
        break
      case 'post':
        response = await request.post(url, data, config);
        break
      case 'put':
        response = await request.post(url, data, { ...config, method: 'put' });
        break
      case 'delete':
        response = await request.post(url, data, { ...config, method: 'delete' });
        break
      default:
        response = await request.post(url, data, config);
    }
    if(response && response.data && response.data.status === undefined){
      response.data.status = response.data.code;
    }
    return response;
  } catch (error) {
    // 区分网络错误和业务错误
    const status = error.code || error.response?.status || -1
    const message = error.msg || error.response?.data?.msg || error.message || '请求失败'

    return {
      status,
      msg: message,
      data: null
    }
  }
}
export default amisRequest
